package apof.model
{
	public class Filter extends ApofModel
	{
		
		public static var LOCAL_WEIGHT:Number=3;
		public static var GLOBAL_WEIGHT:Number=1;
		
		public var fid:int;
		public var keyword:String;
		public var targetCtid:int;
		public var uid:int;
		public var user:User;
		
		public var localhits:int=1;
		public var localtotal:int=2;
		public var hits:int=1;
		public var total:int=100;
		public var newhits:int=0;
		public var newtotal:int=0;

		public var target:ConsumeType=null;

		
		//private static var init:Boolean = onInit();
		public static function onInit():Boolean {
			var pt:Object=prototype;
			pt.classname="Filter";		
			pt.fields=["fid","keyword","targetCtid","uid","localhits","localtotal","hits","total","newhits","newtotal"];
			pt.fieldTypes=["INT","VARCHAR(60)","int","INT","int","int","int","int","int","int"];
			pt.primaryKey="fid";
			pt.foreignKey={	"uid":			{"linkto":User,			"aggregate":false,	"ref":"user",	"peerlink":"consumeTypes"},
							"targetCtid":	{"linkto":ConsumeType,	"aggregate":false,	"ref":"target",	"peerlink":null}
							};
			return true;
		}
	
		public override function get classInfo():Object {return prototype;}
		public static function get classInfo():Object {return prototype;}	
		
		public function access(name:String):Boolean{
			return name.indexOf(keyword)>-1;
		}	
		
		/**
		 * 算法：按本地命中数和总数计算的本地命中率localRatio。同理计算得全局命中率globalRatio。
		 * 1-localRatio为本地失误率。1-globalRatio为全局失误率。
		 * 将这两个数值加权几何平均，得到结果作为本次预测的失误率估计值。权重分别为LOCAL_WEIGHT和GLOBAL_WEIGHT。
		 * 1-（失误率估计值），即为本次预测的命中率估计值。
		 * **/
		public function hitRatio():Number{
			var localRatio:Number=Number(localhits)/localtotal;
			var globalRatio:Number=Number(hits)/total;
			return 1-Math.pow(
				Math.pow((1-localRatio),LOCAL_WEIGHT)*Math.pow((1-globalRatio),GLOBAL_WEIGHT),
				1.0/(LOCAL_WEIGHT+GLOBAL_WEIGHT)
				);
		}
		
		/**
		 * 反馈一次用户选择的结果。
		 * return : 本filter是否被更新
		 * **/
		public function feedback(name:String,resultCtid:int):Boolean {
			if(access(name)) {
				total+=1;
				localtotal+=1;
				newtotal+=1;
				if(resultCtid==targetCtid) {
					hits+=1;
					localhits+=1;
					newhits+=1;
				}
				return true;
			}
			return false;
		}
	}
}